package com.quyunshuo.module.home.fragment.home

import android.content.Context
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.quyunshuo.edwinusetime.base.BaseApplication
import com.quyunshuo.edwinusetime.base.mvvm.vm.BaseViewModel
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.manager.AppUsage
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import java.util.Calendar
import javax.inject.Inject

/**
 * @author DBoy 2021/7/6 <p>
 * - 文件描述 : ViewModel再ViewPager2的Fragment中会随着Fragment执行[Fragment.onDestory]一同销毁。
 * 所以一些需要长期保存的变量数据，不适合保存再ViewModel，考虑使用[ViewStatusHelper]保存页面上部分数据，
 * 页面恢复的时候再交给ViewModel处理,例如[recreatedCont]
 */
@HiltViewModel
class HomeViewModel @Inject constructor() :
    BaseViewModel() {


    @Inject
    lateinit var repository: HomeRepository


    private val _appUsageList = MutableStateFlow<List<AppUsage>>(emptyList())
    val appUsageList: StateFlow<List<AppUsage>> = _appUsageList.asStateFlow()

    private val _loading = MutableStateFlow(false)
    val loading: StateFlow<Boolean> = _loading.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()

    fun loadAppUsageStats(context: Context,days: Int = 1) {
        _loading.value = true
        _error.value = null

        viewModelScope.launch {
            try {
                val stats = repository.getAppUsageStats(context,days)
                _appUsageList.value = stats
                Log.d("wenlong", "loadAppUsageStats: ${stats}")
            } catch (e: Exception) {
                _error.value = "无法获取应用使用数据: ${e.message}"
                Log.d("wenlong", "_error: ${e.message}")
            } finally {
                _loading.value = false
            }
        }
    }

}
